import 'package:flutter/material.dart';
import 'package:flutter2/colors.dart';
import 'package:flutter2/http/api.dart';
import 'package:flutter2/http/dio_manager.dart';
import 'package:flutter2/item/item_period.dart';
import 'package:flutter2/model/product_entity.dart';
import 'package:flutter2/ui/sheet.dart';
import 'package:flutter2/utils/string.dart';
import 'package:flutter2/widget/base/base_container.dart';
import 'package:flutter2/widget/base/normal_button.dart';
import 'package:flutter2/widget/base/normal_text.dart';
import 'package:flutter2/widget/tip_view.dart';
import 'package:flutter2/widget/title_bar.dart';

class LoanPage extends StatefulWidget {
  const LoanPage({super.key});

  @override
  State<LoanPage> createState() => _LoanPageState();
}

class _LoanPageState extends State<LoanPage> {
  final List<String> _amountList = [];
  final Set<int> _periodList = {};
  final List<ProductDetail> _products = [];
  late ProductDetail _curProduct;
  late int _curPeriod;
  String _curAmt = "";

  @override
  void initState() {
    super.initState();
    DioManager.request<ProductEntity>(
      path: HttpApi.getProduct,
      onSuccess: (data) {
        _products.addAll(data?.details ?? []);
        if (_products.isEmpty) return;
        for (var element in _products) {
          _periodList.add(element.period);
        }
        _curPeriod = _periodList.first;
        _curProduct = _getCurProducts().first;
        setAmounts();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: TitleBar.buildAppBar(
        title: "确认借款",
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                "C6F9D4".toColor(),
                "C6F9D4".toColor(),
              ],
            ),
          ),
        ),
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              "C6F9D4".toColor(),
              "22C6F9D4".toColor(),
              mainBg,
            ],
          ),
        ),
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    if (_periodList.isNotEmpty) ...[
                      buildTop(),
                      buildPeriod(),
                      SizedBox(
                        height: 10,
                      ),
                      buildDuration(),
                    ],
                  ],
                ),
              ),
            ),
            if (_periodList.isNotEmpty) ...[
              BaseContainer(
                margin: EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                padding: EdgeInsets.symmetric(horizontal: 20),
                height: 60,
                width: double.infinity,
                radius: 10,
                background: Colors.yellow,
                child: Row(
                  children: [
                    Expanded(
                      child: NormalText(
                        text: r"$" + _curAmt,
                        fontColor: mainText,
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    NormalButton(
                      enable: true,
                      height: 40,
                      text: "Dinero ahora",
                    ),
                  ],
                ),
              )
            ]
          ],
        ),
      ),
    );
  }

  setAmounts() {
    _amountList.clear();
    var max = _curProduct.max;
    var min = _curProduct.min;
    var inc = _curProduct.internal;
    var step = (max - min) / inc;
    for (int i = 0; i < step; i++) {
      _amountList.add((max - i * inc).toString());
    }
    _curAmt = _amountList.first;
    setState(() {});
  }

  List<ProductDetail> _getCurProducts() {
    return _products.where((element) {
      return element.period == _curPeriod;
    }).toList();
  }

  Widget buildDuration() {
    return BaseContainer(
      margin: EdgeInsets.symmetric(horizontal: 16),
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20),
      width: double.infinity,
      radius: 10,
      background: Colors.white,
      child: GridView.count(
        childAspectRatio: 1.5,
        shrinkWrap: true,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        children: _getCurProducts().map((e) {
          return ItemPeriod(
            select: _curProduct == e,
            text: "${e.duration} dias",
            click: () {
              if (_curProduct == e) return;
              _curProduct = e;
              setAmounts();
            },
          );
        }).toList(),
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 3,
      ),
    );
  }

  Widget buildPeriod() {
    return BaseContainer(
      margin: EdgeInsets.symmetric(horizontal: 16),
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20),
      width: double.infinity,
      radius: 10,
      background: Colors.white,
      child: GridView.count(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          crossAxisCount: 6,
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
          children: _periodList.map((e) {
            return ItemPeriod(
                select: _curPeriod == e,
                text: e.toString(),
                click: () {
                  if (_curPeriod == e) return;
                  _curPeriod = e;
                  _curProduct = _getCurProducts().first;
                  setAmounts();
                });
          }).toList()),
    );
  }

  Widget buildTop() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15, horizontal: 16),
      margin: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      width: double.infinity,
      decoration: BoxDecoration(
        image: DecorationImage(
          fit: BoxFit.fill,
          image: AssetImage("bg_loan_top".toImage()),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TipView(
            margin: EdgeInsets.symmetric(horizontal: 0, vertical: 10),
            icon: "cb_checked".toImage(),
            width: 15,
            height: 15,
            fontColor: btnColor,
            text: "Su préstamo ha sido aprobado. Su límite actual es de XXX. Puede utilizarlo de inmediato.",
          ),
          NormalText(
            text: "Monto",
            fontColor: mainText2,
            fontWeight: FontWeight.bold,
            fontSize: 14,
          ),
          GestureDetector(
            onTap: () {
              SheetData.showItems(
                data: _amountList,
                call: (item, index) {
                  _curAmt = _amountList[index];
                  setState(() {});
                },
              );
            },
            child: Row(
              children: [
                NormalText(
                  text: r"$",
                  fontSize: 56,
                  fontColor: mainText,
                ),
                Expanded(
                  child: NormalText(
                    text: _curAmt,
                    fontSize: 56,
                    fontColor: mainText,
                  ),
                ),
                Image.asset(
                  "ic_right".toImage(),
                  width: 16,
                  height: 16,
                ),
              ],
            ),
          ),
          Container(
            width: double.infinity,
            height: 0.5,
            color: mainText3,
          ),
          SizedBox(
            height: 10,
          ),
          TipView(
            margin: EdgeInsets.symmetric(horizontal: 0),
            width: 16,
            height: 16,
            icon: "ic_tip".toImage(),
            background: tipColorDark,
            text: "Mejora tu Crédito y Sube de Nivel",
            fontColor: mainText2,
          )
        ],
      ),
    );
  }
}
